﻿

using IotClientService.Models.Lg;
using IotClientService.Services;
using IotContract.Enums;
using System;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 拆盘机   日志中缺少801
/// 电池取出发送顺序：
///1.933：上位机发送托盘到达 934:FMS 回复此托盘是否 NG
///2.801：上位机邀请电池位置 802：FMS 发送电池位置
///3.905（S）：上位机告知作业开始 906:FMS 应答
///4.905（E）：上位机告知作业结束 906：FMS 应答
///5.937：上位机告知托盘出去 938：FMS 应答
///其他为状态报告，FMS 邀请或上位机主动发送
/// </summary>
public class LgHandleDisAssemble:LgHandleBase
{
    public LgHandleDisAssemble(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
    }

    public override IotEquipType EquipType { get; set; } = IotEquipType.DAEB;
    /// <summary>
    /// 处理消息 
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
       
        switch (msg.Command)
        {
          
            // 作业开始/结束报告，上位机报告
            case "905":
                replyCmd = "906";
               await Handle905(msg, replyCmd);
                break;
            // 设备状态报告指示回应，主动发送909获取状态
            case "910":
               await Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告，待机状态变设备运行状态或设备运行状态变设备待机
            case "913":
               await Handle913(msg, "913");
                break;
            // 作业mode报告，设备模式切换时告知，如自动模式切换手动模式，反过来也是一样
            case "917":
                replyCmd = "918";
               await Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请，上位机和 FMS 相互连接状态
            case "925":
                replyCmd = "926";
               await Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
               await Handle926(msg, "926");
                break;
            // Tray Load报告 上位机告知 FMS 托盘到达
            case "933":
                replyCmd = "934";
               await Handle933(msg, replyCmd);
                break;
            // 托盘出库完成报告，上位机告知托盘要出库，没有937
            case "937":
                replyCmd = "938";
               await Handle937(msg, replyCmd);
                break;
            // 未知命令,错误
            case "981":
               await Handle981(msg, "981");
                break;
            // 设备Trouble报告，设备发生异常告知FMS
            case "985":
               await Handle985(msg, "985");
                break;
            // NG List邀请，上位机邀请 FMS 发送 NG 电池位置
            case "801":
                replyCmd = "802";
               await Handle801(msg, replyCmd);
                break;
            case "804":
                replyCmd = "805";
               await Handle804(msg, replyCmd);
                break;

            // 设置时间指示
            case "999":
               await Handle999(msg, replyCmd);
                break;
            default:
                // send 981
               await Handle981(msg, "981");
                break;
        }
        return true;
    }
   
    /// <summary>
    /// 验证
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle804(LgMsgInfo msg, string replyCmd)
    {


        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }

    /// <summary>
    /// 作业开始/结束报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle905(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
       
        // 托盘
        string tray = msg.Message.Substring(18, 10);

        // S:作业开始  E:作业完成
        string status = msg.Message.Substring(38, 1);

        var result= await Api.CommitDisAssembleReport(new Models.Lg.Remote.LgTrayReportRequest
        {
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Tray = tray,
            Status = status,
        });
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        sendMsg.Body = $"{ret}{status}";
        sendMsg.IsSend = true;
        Equip.Remark = $"tray:{tray}-{status}";
        InvokeSend(sendMsg);

    }
   
   
   
    /// <summary>
    /// Tray Load报告，下发挑选位置和电池码
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        var tray = msg.Message.Substring(18, 10);
       
        Equip.Remark = $"tray load:{tray}";

        
        Equip.Obj = tray;

        var result = await Api.CommitDisAssembleTrayEnter(new Models.Lg.Remote.LgTrayEnterRequest
        {
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Tray = tray

        });
        // 0:ok 1:ng  2:bypass 
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        #region 传输body
        var trayCode = tray.PadRight(20, '0');

        // 0001-9999NG
        var ng = result.Result?.NgCodes?.FirstOrDefault() ?? "0000";
        //var ng = "0000";
        #endregion
        sendMsg.Body = $"{ret}{ng}{tray.PadRight(20,'0')}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }
    /// <summary>
    /// 托盘出库完成报告，没有捉到937
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle937(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        var tray = msg.Message.Substring(18, 10);

       
        Equip.Obj = "";
      

        Equip.Remark = $"tray out:{tray}";


       var result= await Api.CommitDisAssembleTrayOut(new Models.Lg.Remote.LgTrayOutRequest
        {
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Tray = tray
        });
        // 0:ok 1:ng
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        #region 传输body

        //var ng = result.Result?.NgCodes?.FirstOrDefault() ?? "0000";

        // 937不是空托盘


        #endregion
        sendMsg.Body = $"{ret}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }
   
    /// <summary>
    /// 上位机邀请 FMS 发送 NG 电池位置
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle801(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        string tray = msg.Message.Substring(18, 4);

        Equip.Remark = $"tray:{tray}";

        var result= await Api.GetTrayPositionResult(new Models.Lg.Remote.LgTrayEnterRequest
        {
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Tray = tray
        });
        int ret = 0; 
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
       
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        // 查询数据

        #region 数据构造

        var trayId=tray.PadRight(20,'0');
        // 长度48  0:空位置  1:有电池
        var positions = result.Result?.CellPosition??"0".PadRight(48,'0');

        sendMsg.Body = $"{trayId}{positions}";

        sendMsg.IsSend = true;

        InvokeSend(sendMsg);

        #endregion
    }

  
}
